<template>
  <div class="product-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="handleAdd">添加商品</el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categories"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="productList" style="width: 100%" v-loading="loading">
        <el-table-column prop="productId" label="ID" width="80" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="categoryName" label="分类" />
        <el-table-column prop="productPrice" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.productPrice?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProducts, deleteProduct } from '@/api/product'
import { getCategories } from '@/api/category'

const loading = ref(false)
const productList = ref([])
const categories = ref([])
const total = ref(0)
const queryParams = ref({
  page: 1,
  pageSize: 10,
  name: '',
  categoryId: ''
})

const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await getProducts(queryParams.value)
    productList.value = Array.isArray(res) ? res : (res.records || [])
    total.value = res.total || productList.value.length
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error(error.message || '获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const res = await getCategories()
    categories.value = Array.isArray(res) ? res : (res.records || [])
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error(error.message || '获取分类列表失败')
  }
}

const handleSearch = () => {
  queryParams.value.page = 1
  fetchProducts()
}

const handleReset = () => {
  queryParams.value = {
    page: 1,
    pageSize: 10,
    name: '',
    categoryId: ''
  }
  fetchProducts()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  fetchProducts()
}

const handleCurrentChange = (val) => {
  queryParams.value.page = val
  fetchProducts()
}

const handleAdd = () => {
  // TODO: 实现添加商品功能
  ElMessage.info('添加商品功能开发中')
}

const handleEdit = (row) => {
  // TODO: 实现编辑商品功能
  ElMessage.info('编辑商品功能开发中')
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(row.productId)
      ElMessage.success('删除成功')
      fetchProducts()
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error(error.message || '删除商品失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.product-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 